<template>
  <div class="emotion-analysis-container">
    <!-- 返回首页按钮 -->
    <router-link to="/" class="back-home-btn">
      <el-icon><ArrowLeft /></el-icon>
      点击返回首页
    </router-link>

    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="main-title">智能情感分析</h1>
      <p class="subtitle">基于AI智能助手的多语言文本情感识别</p>
    </div>

    <!-- 服务状态卡片 -->
    <el-card class="status-card" v-loading="loadingStatus">
      <template #header>
        <div class="card-header">
          <span><i class="el-icon-monitor"></i> 服务状态</span>
          <el-tag :type="serviceStatus?.available ? 'success' : 'danger'">
            {{ serviceStatus?.available ? '在线' : '离线' }}
          </el-tag>
        </div>
      </template>
      <div v-if="serviceStatus" class="status-content">
        <p><strong>模型:</strong> {{ serviceStatus.model || '未配置' }}</p>
        <p><strong>消息:</strong> {{ serviceStatus.message }}</p>
      </div>
    </el-card>

    <!-- 功能区域 -->
    <div class="features-grid">
      <!-- 单文本分析 -->
      <el-card class="feature-card single-analysis">
        <template #header>
          <div class="card-header">
            <span><i class="el-icon-edit"></i> 单文本情感分析</span>
          </div>
        </template>
        <el-input
          v-model="singleText"
          type="textarea"
          :rows="4"
          placeholder="请输入要分析的文本内容..."
          maxlength="500"
          show-word-limit
          class="text-input"
        />
        <el-button
          type="primary"
          @click="analyzeSingleText"
          :loading="loadingSingle"
          class="analyze-btn"
          :disabled="!singleText.trim()"
        >
          <i class="el-icon-search"></i> 分析情感
        </el-button>
        
        <!-- 单文本结果 -->
        <div v-if="singleResult" class="result-display">
          <el-divider>分析结果</el-divider>
          <div class="emotion-result">
            <el-tag 
              :type="getEmotionType(singleResult.emotion)" 
              size="large"
              class="emotion-tag"
            >
              {{ singleResult.emotion || '未知' }}
            </el-tag>
            <span class="confidence">置信度: {{ (singleResult.confidence * 100).toFixed(1) }}%</span>
          </div>
          <div class="raw-result">
            <p><strong>原始标签:</strong> {{ singleResult.raw_label }}</p>
            <p><strong>详细分数:</strong></p>
            <div class="score-list">
              <span 
                v-for="item in singleResult.all_results" 
                :key="item.label"
                class="score-item"
              >
                {{ item.label }}: {{ (item.score * 100).toFixed(1) }}%
              </span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 批量分析 -->
      <el-card class="feature-card batch-analysis">
        <template #header>
          <div class="card-header">
            <span><i class="el-icon-document-copy"></i> 批量文本分析</span>
          </div>
        </template>
        <el-input
          v-model="batchTexts"
          type="textarea"
          :rows="6"
          placeholder="请输入多行文本，每行一个..."
          class="text-input"
        />
        <el-button
          type="success"
          @click="analyzeBatchTexts"
          :loading="loadingBatch"
          class="analyze-btn"
          :disabled="!batchTexts.trim()"
        >
          <i class="el-icon-document-checked"></i> 批量分析
        </el-button>

        <!-- 批量结果 -->
        <div v-if="batchResults.length > 0" class="result-display">
          <el-divider>批量分析结果</el-divider>
          <el-table :data="batchResults" style="width: 100%" class="results-table">
            <el-table-column prop="text" label="文本" width="300" show-overflow-tooltip />
            <el-table-column label="情感" width="100">
              <template #default="{ row }">
                <el-tag :type="getEmotionType(row.emotion)" size="small">
                  {{ row.emotion || '未知' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="置信度" width="100">
              <template #default="{ row }">
                {{ (row.confidence * 100).toFixed(1) }}%
              </template>
            </el-table-column>
            <el-table-column label="状态" width="80">
              <template #default="{ row }">
                <el-icon :style="{ color: row.success ? '#67C23A' : '#F56C6C' }">
                  <CircleCheck v-if="row.success" />
                  <CircleClose v-else />
                </el-icon>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>

    <!-- 模型信息卡片 -->
    <el-card class="model-info-card" v-if="modelInfo">
      <template #header>
        <div class="card-header">
          <span><i class="el-icon-info"></i> 模型信息</span>
          <el-button type="text" @click="getModelInfo">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </div>
      </template>
      <div class="model-details">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="模型名称">{{ modelInfo.model_name }}</el-descriptions-item>
          <el-descriptions-item label="提供商">{{ modelInfo.provider }}</el-descriptions-item>
          <el-descriptions-item label="任务类型">{{ modelInfo.task }}</el-descriptions-item>
          <el-descriptions-item label="API密钥">{{ modelInfo.api_key_required ? '必需' : '可选' }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="features-section">
          <h4>支持功能</h4>
          <el-tag 
            v-for="feature in modelInfo.features" 
            :key="feature"
            type="info"
            class="feature-tag"
          >
            {{ feature }}
          </el-tag>
        </div>
        
        <div class="languages-section">
          <h4>支持语言</h4>
          <el-tag 
            v-for="lang in modelInfo.supported_languages" 
            :key="lang"
            class="language-tag"
          >
            {{ lang }}
          </el-tag>
        </div>
      </div>
    </el-card>

    <!-- 错误提示 -->
    <el-dialog v-model="errorDialogVisible" title="错误提示" width="30%">
      <p>{{errorMessage}}</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="errorDialogVisible = false">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ArrowLeft, CircleCheck, CircleClose } from '@element-plus/icons-vue'
import axios from 'axios'

// API基础URL
const API_BASE_URL = 'http://localhost:5000'

// 响应式数据
const singleText = ref('')
const singleResult = ref<any>(null)
const batchTexts = ref('')
const batchResults = ref<any[]>([])
const serviceStatus = ref<any>(null)
const modelInfo = ref<any>(null)
const loadingStatus = ref(false)
const loadingSingle = ref(false)
const loadingBatch = ref(false)
const errorDialogVisible = ref(false)
const errorMessage = ref('')

// 获取服务状态
const getServiceStatus = async () => {
  loadingStatus.value = true
  try {
    const response = await axios.get(`${API_BASE_URL}/api/emotion-analysis/status`)
    serviceStatus.value = response.data
  } catch (error) {
    showError('获取服务状态失败: ' + (error as any).message)
  } finally {
    loadingStatus.value = false
  }
}

// 获取模型信息
const getModelInfo = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/emotion-analysis/model-info`)
    modelInfo.value = response.data
  } catch (error) {
    showError('获取模型信息失败: ' + (error as any).message)
  }
}

// 单文本分析
const analyzeSingleText = async () => {
  if (!singleText.value.trim()) {
    showError('请输入要分析的文本')
    return
  }
  
  loadingSingle.value = true
  try {
    const response = await axios.post(`${API_BASE_URL}/api/emotion-analysis`, {
      text: singleText.value.trim()
    })
    singleResult.value = response.data
  } catch (error) {
    showError('分析失败: ' + (error as any).message)
  } finally {
    loadingSingle.value = false
  }
}

// 批量文本分析
const analyzeBatchTexts = async () => {
  if (!batchTexts.value.trim()) {
    showError('请输入要分析的文本')
    return
  }
  
  const texts = batchTexts.value.split('\n').filter(text => text.trim())
  if (texts.length === 0) {
    showError('请输入有效的文本内容')
    return
  }
  
  loadingBatch.value = true
  try {
    const response = await axios.post(`${API_BASE_URL}/api/emotion-analysis/batch`, {
      texts: texts
    })
    batchResults.value = response.data.results
  } catch (error) {
    showError('批量分析失败: ' + (error as any).message)
  } finally {
    loadingBatch.value = false
  }
}

// 获取情感类型对应的标签颜色
const getEmotionType = (emotion: string): string => {
  const emotionMap: Record<string, string> = {
    '积极': 'success',
    '消极': 'danger',
    '中性': 'info'
  }
  return emotionMap[emotion] || 'warning'
}

// 显示错误信息
const showError = (message: string) => {
  errorMessage.value = message
  errorDialogVisible.value = true
}

// 页面加载时初始化
onMounted(() => {
  getServiceStatus()
  getModelInfo()
})
</script>

<style scoped>
@import '../assets/EmotionAnalysis.css'
</style>
